//
//  JRMFMobile.m
//  JRMFMobileVerify
//
//  Created by Criss on 2017/12/25.
//  Copyright © 2017年 SONG. All rights reserved.
//

#import "JRMFMobile.h"
// 系统库
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <objc/message.h>
#import <UIKit/UIKit.h>

// 私有类
#import "NSString+JRMFEncrypt.h"
#import "JRMFError.h"

#define URL_CU @"http://open.wostore.cn/openapi/networkauth/precheck"
#define JRMF_STATICS  @"https://api-collection2.jrmf360.com/api/v1/mobileDate/collectData.shtml"

#define CU_SUCCESS_CODE 0
#define CM_SUCCESS_CODE 103000
#define CT_SUCCESS_CODE 0

/**< 联通 */
static  NSString * APP_ID_CU  ;
static  NSString * APP_KEY_CU ;

/**< 移动 */
static  NSString * APP_ID_CM  ;
static  NSString * APP_KEY_CM ;

/**< 电信 */
static  NSString * APP_ID_CT;
static  NSString * APP_KEY_CT;
static  NSString * tokenType_CT;

/**< 金融魔方 */
static  NSString * APP_ID_JRMF;
static  NSString * APP_KEY_JRMF;

typedef void(^RequestBlock)(NSError * er,id obj);

typedef NS_ENUM(NSUInteger, JRMFNetWorkType) {
    JRMFNetWorkTypeUN,
    JRMFNetWorkTypeWWAN,
    JRMFNetWorkTypeWiFi,
};
@implementation JRMFMobile


#pragma mark - ================================初始化=================================
+ (void)instanceJRMFWith:(JRMFInfoModel*)infoModel
{
    /**< 移动 */
    APP_ID_CM  = infoModel.CM_APPID;
    APP_KEY_CM = infoModel.CM_APPKEY;
    
    /**< 电信 */
    APP_ID_CT  = infoModel.CT_APPID;
    APP_KEY_CT = infoModel.CT_APPKEY;
    
    /**< 联通 */
    APP_ID_CU  = infoModel.CU_APPID;
    APP_KEY_CU = infoModel.CU_APPKEY;
    
    /**< 金融魔方 */
    APP_ID_JRMF  = infoModel.JRMF_APPID;
    APP_KEY_JRMF = infoModel.JRMF_APPKEY;
    
    // 添加统计
    [JRMFMobile doUpdateStatistics];
}
#pragma mark - ================================公共方法================================
+(void)getDeviceToken:(JRMFResult)block
{
    if (!APP_ID_JRMF || APP_ID_JRMF.length == 0) {
        block(nil,JRMFMobileTypeUN,[JRMFError jrmfErrorWithDes:@"请添加金融魔方 appID" code:999]);
        return;
    }
    
    /*
     1.获取设备运营商类型
     2.调用对应sdk接口
     3.返回信息
     */
    
    NSInteger type = [JRMFMobile getMobileType];
    switch (type) {
        case JRMFMobileTypeCM:/**< 移动 */
            [JRMFMobile getDeviceTokenFromCM:block];
            break;
        case JRMFMobileTypeCT:/**< 电信 */
            [JRMFMobile getDeviceTokenFromCT:block];
            break;
        case JRMFMobileTypeCU:/**< 联通 */
            [JRMFMobile getDeviceTokenFromCU:block];
            break;
        default:
            block(nil,JRMFMobileTypeUN,[JRMFError jrmfErrorWithDes:@"获取运营商信息失败" code:999]);
            break;
    }
}

+(NSString *)getCurrentVersion
{
    return @"1.0.0";
}

#pragma mark - ================================私有方法================================


/**
 电信
 */
+ (void)getDeviceTokenFromCT:(JRMFResult)block
{
    // 判断appid appkey
    if (!APP_ID_CT || APP_ID_CT.length == 0) {
        block(nil,JRMFMobileTypeCT,[JRMFError jrmfErrorWithDes:@"请添加电信 appID" code:999]);
        return;
    }
    
    if (!APP_KEY_CT || APP_KEY_CT.length == 0) {
        block(nil,JRMFMobileTypeCT,[JRMFError jrmfErrorWithDes:@"请添加电信 appKey" code:999]);
        return;
    }
    
    Class CTLogin = NSClassFromString(@"EAccount");
    
    if (CTLogin) {
        // 初始化sdk
        if ([CTLogin respondsToSelector:NSSelectorFromString(@"initWithSelfKey:appSecret:appName:")]) {
            ((void *(*)(id,SEL,id,id,id))objc_msgSend)(CTLogin,NSSelectorFromString(@"initWithSelfKey:appSecret:appName:"),APP_ID_CT,APP_KEY_CT,@"金融魔方");
            
            // 取号
            if ([CTLogin respondsToSelector:NSSelectorFromString(@"preGetMobileAccessCode:completion:failure:")]) {
                
                // 成功回调
                void(^ResultBlock)(NSDictionary *) = ^(NSDictionary * resultDic) {
                    if ([resultDic[@"result"] intValue] == CT_SUCCESS_CODE) {
                        block(resultDic[@"accessCode"],JRMFMobileTypeCT,nil);
                    }else{
                        block(nil,JRMFMobileTypeCT,[JRMFError jrmfErrorWithDes:resultDic[@"msg"] code:[resultDic[@"result"] intValue]]);
                    }
                };
                
                // 失败回调
                void(^ErrorBlock)(NSError *) = ^(NSError *error) {
                    block(nil,JRMFMobileTypeCT,error);
                };
                
                ((void *(*)(id,SEL,id,typeof(ResultBlock),typeof(ErrorBlock)))objc_msgSend)(CTLogin,NSSelectorFromString(@"preGetMobileAccessCode:completion:failure:"),tokenType_CT,ResultBlock,ErrorBlock);
            }
        }else{
            block(nil,JRMFMobileTypeUN,[JRMFError defaultError]);
        }
    }else{
        block(nil,JRMFMobileTypeCT,[JRMFError jrmfErrorWithDes:@"请添加电信认证sdk" code:999]);
    }
}

/**
 移动
 */
+ (void)getDeviceTokenFromCM:(JRMFResult)block
{
    // 判断appid appkey
    if (!APP_ID_CM || APP_ID_CM.length == 0) {
        block(nil,JRMFMobileTypeCM,[JRMFError jrmfErrorWithDes:@"请添加移动 appID" code:999]);
        return;
    }
    
    if (!APP_KEY_CM || APP_KEY_CM.length == 0) {
        block(nil,JRMFMobileTypeCM,[JRMFError jrmfErrorWithDes:@"请添加移动 appKey" code:999]);
        return;
    }
    
    Class CMLogin = NSClassFromString(@"TYRZUILogin");
    
    if (CMLogin) {
        if ([CMLogin respondsToSelector:NSSelectorFromString(@"initializeWithAppId:appKey:")]) {
            ((void *(*)(id,SEL,id,id))objc_msgSend)(CMLogin,NSSelectorFromString(@"initializeWithAppId:appKey:"),APP_ID_CM,APP_KEY_CM);
            
            // 回调处理
            void(^ResultBlock)(id) = ^(id obj) {
                NSString * resultCode = obj[@"resultCode"];
                if ([resultCode integerValue] == CM_SUCCESS_CODE) {
                    block(obj[@"token"],JRMFMobileTypeCM,nil);
                }else{
                    block(nil,JRMFMobileTypeCM,[JRMFError jrmfErrorWithDes:obj[@"desc"] code:[resultCode intValue]]);
                }
            };
            
            if ([CMLogin respondsToSelector:NSSelectorFromString(@"getTokenImpWithComplete:")]) {
                ((void *(*)(id,SEL,typeof(ResultBlock)))objc_msgSend)(CMLogin,NSSelectorFromString(@"getTokenImpWithComplete:"),ResultBlock);
            }
        }
    }else{
        block(nil,JRMFMobileTypeCM,[JRMFError jrmfErrorWithDes:@"请添加移动认证sdk" code:999]);
    }
}

/**
 联通
 */
+ (void)getDeviceTokenFromCU:(JRMFResult)block
{
    
    // 判断appid appkey
    if (!APP_ID_CU || APP_ID_CU.length == 0) {
        block(nil,JRMFMobileTypeCU,[JRMFError jrmfErrorWithDes:@"请添加联通 appID" code:999]);
        return;
    }
    
    if (!APP_KEY_CU || APP_KEY_CU.length == 0) {
        block(nil,JRMFMobileTypeCU,[JRMFError jrmfErrorWithDes:@"请添加联通 appKey" code:999]);
        return;
    }
    
    // 调用接口
    // 拼接接口名
    NSString * uuidStr = [[[[JRMFMobile getMobileUUID] stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString] substringToIndex:26];
    NSString * requestUrl = [NSString stringWithFormat:@"%@?unikey=010005%@",URL_CU,uuidStr];
    
    // Authorization 加密
    NSDictionary * aDic = @{@"timeStamp":[JRMFMobile getCurrentTimeInterval]};
    NSData * authorizationData = [NSJSONSerialization dataWithJSONObject:aDic options:0 error:nil];
    NSString * authorizationStr = [[NSString alloc]initWithData:authorizationData encoding:NSUTF8StringEncoding];
    authorizationStr = [authorizationStr threeDesAndBase64EncOrDec:kCCEncrypt key:APP_KEY_CU];
    
    // 请求头
    NSDictionary * hDic = @{@"client_id":APP_ID_CU,
                            @"client_type":@"30300",
                            @"version":@"1.5",
                            @"Authorization":authorizationStr};
    
    // 发送请求
    [JRMFMobile requestWith:@"GET" requestUrl:requestUrl headerDic:hDic paramDic:nil compelte:^(NSError *er, id obj) {
        if (!er) {
            NSInteger codeValue = [obj[@"code"] integerValue];
            if (codeValue == CU_SUCCESS_CODE) {
                // 获取成功
                NSString * dataStr = [obj[@"data"] threeDesAndBase64EncOrDec:kCCDecrypt key:APP_KEY_CU];
                NSData * dataData  = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
                
                NSError * error = nil;
                NSDictionary * dataDic = [NSJSONSerialization JSONObjectWithData:dataData options:0 error:&error];
                if (!error) {
                    block(dataDic[@"accessCode"],JRMFMobileTypeCU,nil);
                }else{
                    block(nil,JRMFMobileTypeCU,error);
                }
            }else{
                block(nil,JRMFMobileTypeCU,[JRMFError jrmfErrorWithDes:obj[@"msg"] code:codeValue]);
            }
        }else{
            block(nil,JRMFMobileTypeCU,er);
        }
    }];
}

/**
 数据统计
 */
+ (void)doUpdateStatistics {
    //* 设置参数
    
    Class jrmfTool = NSClassFromString(@"JYangLib");
    
    if (jrmfTool) {
       NSString * str = ((NSString *(*)(id,SEL))objc_msgSend)(jrmfTool,NSSelectorFromString(@"GetJYangToolLibMsg"));
        NSMutableString * param = [[NSMutableString alloc] initWithString:[str desEncryWithKey:@"JRMFMobileVerify"]];
        [param appendFormat:@"&sdkVersion=%@&partnerId=%@&custUid=%@&sdkName=%@&isProDuct=%d", [JRMFMobile getCurrentVersion], APP_ID_JRMF, @"", @"号码校验", 1];
       
        void(^SuccessBlock)(NSURLSessionDataTask *task, NSDictionary *responseObj) = ^(NSURLSessionDataTask *task, NSDictionary *responseObj) {
            NSLog(@"成功");
        };
        
        void(^FailBlock)(NSURLSessionDataTask *task, NSError *error) = ^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"%@", error);
        };
        
        ((void *(*)(id,SEL,id,id,typeof(SuccessBlock),typeof(FailBlock)))objc_msgSend)(jrmfTool,NSSelectorFromString(@"postGetRequestWithLink:parameter:Success:Fail:"),JRMF_STATICS,param,SuccessBlock,FailBlock);
        
    }
}


/**
 公共请求方法
 */
+ (void)requestWith:(NSString *)mathod requestUrl:(NSString *)url headerDic:(NSDictionary *)hDic paramDic:(NSDictionary *)param compelte:(RequestBlock)block
{
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
    
    // 设置请求方式
    [request setHTTPMethod:mathod];
    
    // 设置请求头
    if (hDic) {
        for (NSString * key in hDic.allKeys) {
            [request setValue:hDic[key] forHTTPHeaderField:key];
        }
    }

    // 设置请求体
    if (param) {
        NSData * paramData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
        [request setHTTPBody:paramData];
    }
    
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)  {
        if (error) {
            block(error,nil);
        }else{
            NSError * err = nil;
            NSDictionary * mdic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
            if (err) {
                block(err,nil);
            }else{
                block(nil,mdic);
            }
        }
    }];

    [task resume];
}

/**
 获取手机运营商类型

 @return 类型
 */
+ (JRMFMobileType)getMobileType
{
    NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    UIView *serviceView = nil;
    Class serviceClass = NSClassFromString([NSString stringWithFormat:@"UIStat%@Serv%@%@", @"usBar", @"ice", @"ItemView"]);
    for (UIView *subview in subviews) {
        if([subview isKindOfClass:[serviceClass class]]) {
            serviceView = subview;
            break;
        }
    }
    if (serviceView) {
        NSString *carrierName = [serviceView valueForKey:[@"service" stringByAppendingString:@"String"]];
        if ([carrierName rangeOfString:@"联通"].length>0) {
            return JRMFMobileTypeCU;
        }else if ([carrierName rangeOfString:@"移动"].length>0){
            return JRMFMobileTypeCM;
        }else if ([carrierName rangeOfString:@"电信"].length>0){
            return JRMFMobileTypeCT;
        }
    }
    return JRMFMobileTypeUN;
}

+(JRMFNetWorkType)getNetWorkInfo{
    NSInteger  networktype = 0;
    NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews];
    NSNumber *dataNetworkItemView = nil;
    
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            dataNetworkItemView = subview;
            break;
        }
    }
    
    switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"]integerValue]) {
        case 0:/**< UN */
            networktype = JRMFNetWorkTypeUN;
            break;
        case 1:/**< 2G */
        case 2:/**< 3G */
        case 3:/**< 4G */
        case 4:/**< LTE */
            networktype = JRMFNetWorkTypeWWAN;
            break;
        case 5:/**< WiFi */
            networktype = JRMFNetWorkTypeWiFi;
            break;
        default:
            break;
            
    }
    return networktype;
}

+ (NSString *)getMobileUUID
{
   return [[UIDevice currentDevice].identifierForVendor UUIDString];
}

+ (NSString *)getCurrentTimeInterval{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval time=[date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}
#pragma mark - ================================系统代理================================

#pragma mark - ================================自定义代理===============================

#pragma mark - ================================网络请求================================

@end


@implementation JRMFInfoModel

@end
